<template>
  <div class="chat-container">
    <div class="pub-username">
      <span>{{ useProductDetailStore().productDetail.nickName }}</span>
    </div>
    <!-- 相关联的商品、价钱和去付款按钮 -->
    <div class="linked-product">
      <img class="product-image" :src="useProductDetailStore().productDetail.image"
        style="border: 1px solid rgba(0, 0, 0, 0.08)" />
      <div class="price">
        <div style="color: red; font-weight: 600; font-size: 24px;">￥{{ useProductDetailStore().productDetail.price }}
        </div>
        <div class="post-type">发货方式：{{ useProductDetailStore().productDetail.postType === 0 ? '邮寄' : '自提' }}</div>
      </div>
      <el-button @click="goToCreateOrder">去付款</el-button>
    </div>
    <!-- 发送者头像和昵称显示 -->
    <div class="message-list" ref="messageListRef">
      <div class="message-item" v-for="message in useChatMessageStore().messages" :key="message.id">
        <!-- 如果是本人消息，则展示在右侧 -->
        <div class="message-mine-item" v-if="message.fromUserId === useUserStore().user.id">
          <div class="message-my-conent">{{ message.content }}</div>
          <div class="user-avatar">
            <el-image class="avatar-item" style="width: 40px;height: 40px;border-radius: 100%"
              :src="message.fromUserAvatar"></el-image>
          </div>
        </div>
        <!-- 如果是对方消息则展示在左侧 -->
        <div class="message-other-item" v-else>
          <div class="user-avatar">
            <el-image class="avatar-item" style="width: 40px;height: 40px;border-radius: 100%"
              :src="message.fromUserAvatar"></el-image>
          </div>
          <div class="message-other-conent">{{ message.content }}</div>
        </div>
      </div>
    </div>
    <!-- 本人用户头像和昵称显示 -->
    <!-- 发送消息输入框和按钮 -->
    <div class="input-wrapper">
      <el-input v-model="useChatMessageStore().content" type="textarea" autosize placeholder="说点什么..."
        @keyup.enter="useChatMessageStore().sendMessage" />
      <!-- 发送按钮 -->
      <el-button :disabled="useChatMessageStore().content === ''" @click="useChatMessageStore().sendMessage"
        color="#fe3b55" circle>发 送</el-button>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { updateChatMessageIsReadApi } from '@/api/chatmessage';
import { useProductDetailStore, useChatMessageStore, useUserStore } from '@/stores'
import { useChatListStore } from '@/stores/modules/chatList';
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 跳转到创建订单页面
const goToCreateOrder = () => {
  router.push({
    path: '/order/create',
    query: {
      productId: useProductDetailStore().productDetail.id
    }
  })
}

// 引用消息列表
const messageListRef = ref<HTMLDivElement | null>(null)
// 滚动到消息列表底部
const scrollToBottom = () => {
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight;
  }
}
// 打开聊天,设置聊天窗口为打开状态
onMounted(() => {
  console.log('打开聊天')
  useChatMessageStore().isChatMessageOpened = useChatMessageStore().chatList.id
  // 初次加载滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
  // 如果存在旧的聊天，则将聊天记录中的发给自己的未读消息设置为已读
  if (useChatMessageStore().messages.length > 0) {
    updateChatMessageIsReadApi(useChatMessageStore().chatList.id)
    // 将本地未读消息里面的发送给自己的消息的isRead设置为1
    useChatMessageStore().messages.forEach((message) => {
      if (message.toUserId === useUserStore().user.id) {
        message.isRead = '1'
      }
    })
    // 将当前聊天的未读消息数量设置为0
    useChatListStore().chatList.find((chat) => chat.id === useChatMessageStore().chatList.id)!.noReadCount = 0
  }
})
// 监听消息变化，滚动到底部
watch(() => useChatMessageStore().messages,
  () => {
    nextTick(() => {
      scrollToBottom()
    })
    // 如果存在旧的聊天，则将聊天记录中的发给自己的未读消息设置为已读
    if (useChatMessageStore().messages.length > 0) {
      updateChatMessageIsReadApi(useChatMessageStore().chatList.id)
      // 将本地未读消息里面的发送给自己的消息的isRead设置为1
      useChatMessageStore().messages.forEach((message) => {
        if (message.toUserId === useUserStore().user.id) {
          message.isRead = '1'
        }
      })
      // 将当前聊天的未读消息数量设置为0
      useChatListStore().chatList.find((chat) => chat.id === useChatMessageStore().chatList.id)!.noReadCount = 0
    }
  },
  { deep: true }
)

// 卸载后关闭聊天,设置聊天窗口为关闭状态
onUnmounted(() => {
  useChatMessageStore().isChatMessageOpened = ''
  console.log('关闭聊天')
})



</script>

<style lang='less' scoped>
.chat-container {
  height: 100%;
  position: relative;

  .pub-username {
    height: 50px;
    font-size: 18px;
    font-weight: 700;
    display: flex;
    align-items: center;
  }

  .linked-product {
    height: 100px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid rgba(0, 0, 0, 0.08);

    .product-image {
      border-radius: 10%;
      height: 70px;
      width: 70px;
      object-fit: cover;
    }

    .price {
      height: 70px;
      padding: 10px 0;
      margin-left: 10px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .post-type {
        font-size: 14px;
        color: var(--dark-font-color);
        white-space: pre-wrap;
        overflow-wrap: break-word;
        margin-bottom: 3px;
      }
    }

    button {
      width: 60px;
      height: 30px;
      border: none;
      background-color: var(--theme-color);
      color: #fff;
      font-size: 14px;
      border-radius: 15px;
      font-weight: 600;
      transition: all 0.2s;
      margin-left: 30px;

      &:hover {
        transform: scale(1.05);
      }
    }
  }

  .message-list {
    overflow-y: auto;
    max-height: calc(100% - 200px);

    &::-webkit-scrollbar {
      width: 5px;
      /* 滚动条宽度 */
    }

    &::-webkit-scrollbar-thumb {
      background-color: rgba(254, 59, 85, 0.6);
      /* 滚动条颜色 */
      border-radius: 10px;
      /* 滚动条圆角 */
    }

    &::-webkit-scrollbar-track {
      background-color: var(--dark-background-color);
      /* 滚动条轨道颜色 */
    }

    &::-webkit-scrollbar-button {
      display: none;
      /* 隐藏上下按钮 */
    }

    .message-item {
      margin-right: 10px;

      .message-mine-item {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
        align-items: center;

        .message-my-conent {
          background: rgba(var(--theme-color-rgb), 0.1);
          color: var(--theme-color);
          font-weight: 600;
          padding: 10px;
          border-radius: 10px;
          margin-right: 10px;
          max-width: 60%;
          word-wrap: break-word;
        }
      }

      .message-other-item {
        margin-top: 20px;
        display: flex;
        justify-content: flex-start;
        align-items: center;

        .message-other-conent {
          background: rgba(var(--theme-blue-color-rgb), 0.1);
          color: var(--theme-blue-color);
          font-weight: 600;
          padding: 10px;
          border-radius: 10px;
          margin-left: 10px;
          max-width: 60%;
          word-wrap: break-word;
        }
      }
    }

  }

  .input-wrapper {
    position: fixed;
    bottom: 10px;
    height: 50px;
    display: flex;
    align-items: center;

    :deep(.el-textarea__inner) {
      background-color: var(--dark-background-color);
      width: 300px;
      border-radius: 20px;
      padding-left: 20px;
      box-shadow: none;
      resize: none;
      caret-color: var(--theme-color);
    }

    button {
      width: 60px;
      height: 30px;
      border: none;
      color: #fff;
      font-size: 14px;
      border-radius: 15px;
      font-weight: 600;
      transition: all 0.2s;
      margin-left: 10px;

      &:hover {
        transform: scale(1.05);
      }
    }
  }

}
</style>
